package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.BootstrapText;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.FileListAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.bean.LawingSiteE;
import com.infore.airsupervise.bean.PolluterE;
import com.infore.airsupervise.ui.fragment.PsonSelectorFragment;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.vincent.filepicker.Constant;
import com.vincent.filepicker.activity.AudioPickActivity;
import com.vincent.filepicker.activity.VideoPickActivity;
import com.vincent.filepicker.filter.entity.AudioFile;
import com.vincent.filepicker.filter.entity.VideoFile;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

import static com.vincent.filepicker.activity.AudioPickActivity.IS_NEED_RECORDER;
import static com.vincent.filepicker.activity.ImagePickActivity.IS_NEED_CAMERA;

/**
 * 执法取证
 */
public class SiteEvidenceCreateActivity extends BaseTitleBarActivity implements AMapLocationListener {

    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.btn_location)
    AwesomeTextView btnLocation;
    @BindView(R.id.tv_lat)
    TextView tvLat;
    @BindView(R.id.tv_lng)
    TextView tvLng;
    @BindView(R.id.rv_file)
    RecyclerView rvFile;

    private final int REQUEST_CODE_GALLERY = 1001;
    @BindView(R.id.btn_search)
    AwesomeTextView btnSearch;

    private PsonSelectorFragment psonSelectorFra; //执法人员选择
    //定位
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private FileListAdapter adapter;
    private List<String> filesList = new ArrayList<>();
    private LawingSiteE.Evidence evidenceE;

    private PolluterE polluterE;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_site_evidence_create);
        ButterKnife.bind(this);
        Intent it = getIntent();
        if (null != it) {
            polluterE = (PolluterE) it.getSerializableExtra("intent_polluter");
            evidenceE = (LawingSiteE.Evidence) it.getSerializableExtra("SiteToEvidence");
        }
        title.setText("创建执法取证");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_CHECK);
        intLocation();
        if (null != evidenceE) {
            setEvidenceData();
        } else {
            evidenceE = new LawingSiteE.Evidence();
            startLoction();
        }
        setPolluterData();
        initView();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        psonSelectorFra = new PsonSelectorFragment();
        getSupportFragmentManager().beginTransaction().
                replace(R.id.low_persons_container, psonSelectorFra, null).commit();
        //设置recyclerView
        rvFile.setLayoutManager(new LinearLayoutManager(ctx));
        adapter = new FileListAdapter(R.layout.item_file, filesList,true);
        rvFile.setAdapter(adapter);
    }

    /**
     * 在编辑时，设置执法取证UI
     */
    private void setEvidenceData() {
        if(null != evidenceE.getFiles()){
            filesList.addAll(evidenceE.getFiles());
        }
        tvLat.setText("经度：" + evidenceE.getLat());
        tvLng.setText("维度：" + evidenceE.getLnt());
        etAddress.setText(evidenceE.getAddress());
    }

    /**
     * 设置污染源UI
     */
    private void setPolluterData(){
        if( null == polluterE){
            return ;
        }
        BootstrapText.Builder builder = new BootstrapText.Builder(ctx);
        builder.addFontAwesomeIcon(FontAwesome.FA_SEARCH)
                .addText(" "+polluterE.getName())
        ;
        btnSearch.setBootstrapText(builder.build());
        btnSearch.setGravity(Gravity.START);
    }

    /**
     * 初始化定位设置
     */
    private void intLocation() {
        locationClient = new AMapLocationClient(ctx);
        locationOption = new AMapLocationClientOption();
        locationClient.setLocationOption(locationOption);
        locationClient.setLocationListener(this);

    }

    /**
     * 开始定位
     */
    private void startLoction() {
        locationClient.startLocation();
        btnLocation.setFontAwesomeIcon(FontAwesome.FA_CIRCLE_O_NOTCH);
        btnLocation.setAnimation(AnimationUtils.loadAnimation(ctx, R.anim.loading_animation));
        btnLocation.setEnabled(false);
    }

    /**
     * 销毁定位
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    /**
     * 打开相册
     */
    private void selectInGallery() {
        //带配置
        FunctionConfig config = new FunctionConfig.Builder()
                .setMutiSelectMaxSize(5)
                .setEnablePreview(true)
                .setEnableCamera(true)
                .build();
        GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY, config, mOnHanlderResultCallback);
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.btn_location, R.id.btn_camera, R.id.btn_video, R.id.btn_voice,R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_location:// 定位
                startLoction();
                break;
            case R.id.btn_camera: //照片
                selectInGallery();
                break;
            case R.id.btn_video: //视频
                Intent intent2 = new Intent(this, VideoPickActivity.class);
                intent2.putExtra(IS_NEED_CAMERA, true);
                intent2.putExtra(Constant.MAX_NUMBER, 5);
                startActivityForResult(intent2, Constant.REQUEST_CODE_PICK_VIDEO);
                break;
            case R.id.btn_voice: //录音
                Intent intent3 = new Intent(this, AudioPickActivity.class);
                intent3.putExtra(IS_NEED_RECORDER, true);
                intent3.putExtra(Constant.MAX_NUMBER, 5);
                startActivityForResult(intent3, Constant.REQUEST_CODE_PICK_AUDIO);
                break;
            case R.id.btn_search : //搜索污染源
                ToastUtil.showShort(ctx, "选择一个污染源");
                JumpUtil.ForResultJumpFromTo(this, PolluterSearchActivity.class, 99, Constants.INTENT_INT_KEY, 1);
                break ;
        }
    }

    @Override
    protected void onRightMenuClick(View view) {
        super.onRightMenuClick(view);
        evidenceE.setFiles(filesList);
        Intent it = new Intent();
        it.putExtra(Constants.INTENT_OBJ_KEY, evidenceE);
        it.putExtra("intent_polluter",polluterE);
        setResult(RESULT_OK, it);
        finish();
    }

    /**
     * 定位监听
     *
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        locationClient.stopLocation();
        btnLocation.setEnabled(true);
        btnLocation.clearAnimation();
        btnLocation.setFontAwesomeIcon(FontAwesome.FA_MAP_MARKER);
        if (null != aMapLocation) {
            if (aMapLocation.getErrorCode() == 0) { //定位成功
                etAddress.setText(aMapLocation.getAddress());
                tvLat.setText("经度：" + aMapLocation.getLatitude());
                tvLng.setText("维度：" + aMapLocation.getLongitude());
                evidenceE.setAddress(aMapLocation.getAddress());
                evidenceE.setLat(aMapLocation.getLatitude());
                evidenceE.setLnt(aMapLocation.getLongitude());
            } else {
                String str_info[] = aMapLocation.getErrorInfo().split(" ");
                ToastUtil.showShort(ctx, str_info[0]);
                etAddress.getText().clear();
                tvLat.setText("经度：0");
                tvLng.setText("纬度：0");
            }
        }
    }

    /**
     * GalleryFinal 相册 的 回调方法
     */
    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (null != resultList) {
                for (PhotoInfo photo : resultList) {
                    filesList.add(photo.getPhotoPath());
                }
                // filesList.addAll(ImageUtil.getInstance().compressOnUpload(resultList)); 压缩图片
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case Constant.REQUEST_CODE_PICK_AUDIO: //录音
                    ArrayList<AudioFile> listAudio = data.getParcelableArrayListExtra(Constant.RESULT_PICK_AUDIO);
                    for (AudioFile file : listAudio) {
                        filesList.add(file.getPath());
                    }
                    break;
                case Constant.REQUEST_CODE_PICK_VIDEO: //视频
                    ArrayList<VideoFile> listVideo = data.getParcelableArrayListExtra(Constant.RESULT_PICK_VIDEO);
                    for (VideoFile file : listVideo) {
                        filesList.add(file.getPath());
                    }
                    break;
                case 99 :
                    polluterE = (PolluterE) data.getSerializableExtra(Constants.INTENT_OBJ_KEY);
                    setPolluterData();
                    break;
            }
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
        if(mOnHanlderResultCallback != null){
            mOnHanlderResultCallback = null ;
        }
    }

}
